import { _decorator, Component, EventTouch, Input, instantiate, Label, Node, UITransform, Vec2, Vec3 } from 'cc';
import { BaseComponent } from '../../Manager/UIManager/BaseComponent';
import { GAME_POP, GAME_PREFAB, GlobalData, SOUND_TYPE } from '../../Data/GlobalData';
import { LittleMajiangBox } from './LittleMajiangBox';
import { PopPass } from '../../Pop/PopPass';
import { DiffGame } from './DiffGame';
const { ccclass, property } = _decorator;

@ccclass('DiffMajiang')
/**
 * 升级难度麻将层
 */
export class DiffMajiang extends BaseComponent {

    //单线数组
    public MajiangLineArray: Node[] = [];

    //其实创建数量
    public MajiangLineCount: number = 27;

    //发牌按钮
    @property(Node)
    private SendBtn: Node = null;

    //点击层
    @property(Node)
    private TouchNode: Node = null;

    //第一个点击
    private FirstClick: Node = null;

    //麻将文本
    @property(Label)
    public MajiangLabel: Label = null;

    //麻将数量
    public MaJiangNum: number = 0;

    //麻将池
    public MajiangPool: string[] = [];

    //空余索引
    public EmptyIndex: number[] = [
        7, 10, 13
    ];

    //锁住索引
    public LockIndex: number[] = [16, 19];

    //游戏场景
    @property(Node)
    public DiffGame: Node = null;

    protected Init(): void {

        for (let i = 0; i < this.MajiangLineCount; i++) {
            let sl: Node = instantiate(app.resManager.Prefabs[GAME_PREFAB.LittleMajiangBox]);
            sl.parent = this.node;
            sl.getComponent(LittleMajiangBox).DiffMajiang = this;
            this.MajiangLineArray.push(sl);
        }

        this.TouchNode.on(Input.EventType.TOUCH_START, this.TouchStart, this);

    }

    /**
     * 更新关卡
     */
    public UpdateLevel(_majiagnnum: number) {

        this.MaJiangNum = _majiagnnum;
        this.MajiangPool = [];

        for (let i = 0; i < this.MaJiangNum; i++) {
            let majiang_name: string = GlobalData.MajiangName[Math.floor(Math.random() * GlobalData.MajiangName.length)];
            for (let j = 0; j < 4; j++) {
                this.MajiangPool.push(majiang_name);
            }
        };
        this.MaJiangNum *= 4
        this.MajiangLabel.string = this.MaJiangNum.toString();

        for (let i = 0; i < this.MajiangLineArray.length; i++) {

            if (this.EmptyIndex.indexOf(i) > -1) {
                this.MajiangLineArray[i].getComponent(LittleMajiangBox).Init([])
            } else if (this.LockIndex.indexOf(i) > -1) {
                this.MajiangLineArray[i].getComponent(LittleMajiangBox).Lock();
            } else {

                // let mj: string[] = [];
                // for (let i = 0; i < 4; i++) {
                //     let mjn: string = this.MajiangPool[Math.floor(Math.random() * this.MajiangPool.length)];
                //     mj.push(mjn);
                //     this.MajiangPool.splice(this.MajiangPool.indexOf(mjn), 1);
                // }
                // this.MajiangLineArray[i].getComponent(LittleMajiangBox).Init(mj);

                let mj: string[] = [];
                let tempPool = [...this.MajiangPool]; // 创建临时池来抽取
                for (let i = 0; i < 4; i++) {
                    let mjn: string;
                    do {
                        // 随机选择一个麻将
                        const randomIndex = Math.floor(Math.random() * tempPool.length);
                        mjn = tempPool[randomIndex];
                        // 检查当前选择的麻将在mj数组中的出现次数不能超过3次
                    } while (mj.filter(m => m === mjn).length >= 3);

                    mj.push(mjn);
                    // 从临时池和主池中都移除使用的麻将
                    tempPool.splice(tempPool.indexOf(mjn), 1);
                    this.MajiangPool.splice(this.MajiangPool.indexOf(mjn), 1);
                }
                this.MaJiangNum -= 4;
                this.MajiangLabel.string = this.MaJiangNum.toString();
                this.MajiangLineArray[i].getComponent(LittleMajiangBox).Init(mj);

            }

        }

        this.MajiangLabel.string = this.MajiangPool.length.toString();
    }

    /**
     * 点击屏幕
     */
    private TouchStart(_e: EventTouch) {
        let click_pos: Vec2 = _e.getUILocation();
        let click_pos_world: Vec3 = this.node.getComponent(UITransform).convertToWorldSpaceAR(new Vec3(click_pos.x, click_pos.y, 0));

        for (let lmb of this.MajiangLineArray) {
            let lmb_pos: Vec3 = this.node.getComponent(UITransform).convertToWorldSpaceAR(lmb.getWorldPosition());

            if (Math.abs(lmb_pos.y - click_pos_world.y) < 90 / 2 &&
                Math.abs(lmb_pos.x - click_pos_world.x) < 230 / 2) {

                if (!lmb.getComponent(LittleMajiangBox).UnLockBtn.active) {
                    if (this.FirstClick) {
                        if (this.FirstClick == lmb) {
                            app.audioManager.PlayEffect(SOUND_TYPE.Boom);
                            this.FirstClick.getComponent(LittleMajiangBox).IamReset();
                        } else {
                            console.log("点击得不同", lmb.getComponent(LittleMajiangBox).ReturnLastIndex(), this.FirstClick.getComponent(LittleMajiangBox).ClickName,
                                lmb.getComponent(LittleMajiangBox).ShowMajiang.length == 0)
                            //判断是否能合成
                            if (lmb.getComponent(LittleMajiangBox).ReturnLastIndex() == this.FirstClick.getComponent(LittleMajiangBox).ClickName ||
                                lmb.getComponent(LittleMajiangBox).ShowMajiang.length == 0) {
                                app.audioManager.PlayEffect(SOUND_TYPE.Boom);
                                lmb.getComponent(LittleMajiangBox).AddClickMajiang(this.FirstClick.getComponent(LittleMajiangBox));
                            } else {
                                app.audioManager.PlayEffect(SOUND_TYPE.Wrong);
                                this.FirstClick.getComponent(LittleMajiangBox).IamWrong();
                            }
                        }
                        this.FirstClick = null;
                    } else {
                        if (lmb.getComponent(LittleMajiangBox).ReturnCanClick()) {
                            app.audioManager.PlayEffect(SOUND_TYPE.Boom);
                            this.FirstClick = lmb;
                            lmb.getComponent(LittleMajiangBox).IamChoose();
                        }
                    }
                }
            }

        }


    }


    /**
     * 判断游戏结束
     */
    public CheckGameOver() {

        //解锁的
        let unlock_node: Node[] = [];

        for (let sl of this.MajiangLineArray) {
            if (!sl.getComponent(LittleMajiangBox).UnLockBtn.active) unlock_node.push(sl);
        }

        for (let un of unlock_node) {
            if (un.getComponent(LittleMajiangBox).ShowMajiang.length > 0) {
                return;
            }
        }

        app.popManager.ShowPop(GAME_POP.PopPass);
        app.popManager.CurrentPop.getComponent(PopPass).Cb = () => {
            app.gameData.GameData.currentlevel++;
            app.gameData.UpdateGameDateLocal();
            this.DiffGame.getComponent(DiffGame).GameStart();
        }

    }

    /**
     * 添加麻将
     */
    public AddMajiang(_lmb: LittleMajiangBox) {
        console.log("进入这里")
        let mj: string[] = [];
        // 如果麻将池为空，直接返回
        if (this.MajiangPool.length === 0) {
            _lmb.Init(mj);
            this.CheckGameOver();
            return;
        }

        let tempPool = [...this.MajiangPool]; // 创建临时池来抽取
        // 获取实际可抽取的数量（最多4个，最少1个）
        const drawCount = Math.min(4, this.MajiangPool.length);

        for (let i = 0; i < drawCount; i++) {
            let mjn: string;
            do {
                // 随机选择一个麻将
                const randomIndex = Math.floor(Math.random() * tempPool.length);
                mjn = tempPool[randomIndex];
                // 检查当前选择的麻将在mj数组中的出现次数不能超过3次
            } while (tempPool.length > 1 && mj.filter(m => m === mjn).length >= 3);

            mj.push(mjn);
            // 从临时池和主池中都移除使用的麻将
            tempPool.splice(tempPool.indexOf(mjn), 1);
            this.MajiangPool.splice(this.MajiangPool.indexOf(mjn), 1);
        }

        this.MaJiangNum -= drawCount;
        this.MajiangLabel.string = this.MaJiangNum.toString();
        _lmb.Init(mj, true);

        //判断游戏是否过关
        this.CheckGameOver();

    }

    /**
     * 更新最大数
     */
    public UpdateMax(_clearindex: number, _sl: Node) {

    }



}




